package com.tianji.learning.service.impl;

import com.tianji.common.utils.DateUtils;
import com.tianji.common.utils.ObjectUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.constants.RedisConstants;
import com.tianji.learning.domain.enums.PointsRecordType;
import com.tianji.learning.domain.po.PointsRecord;
import com.tianji.learning.domain.vo.PointsStatisticsVO;
import com.tianji.learning.mapper.PointsRecordMapper;
import com.tianji.learning.service.IPointsRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.tianji.learning.constants.RedisConstants.POINTS_BOARD_KEY_PREFIX;

/**
 * <p>
 * 学习积分记录，每个月底清零 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-28
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PointsRecordServiceImpl extends ServiceImpl<PointsRecordMapper, PointsRecord> implements IPointsRecordService {

    private final StringRedisTemplate redisTemplate;

    @Override
    public void addPointsRecord(PointsRecord pointsRecord) {
        this.save(pointsRecord);
        String key1 = POINTS_BOARD_KEY_PREFIX + LocalDateTime.now().format(DateUtils.POINTS_BOARD_SUFFIX_FORMATTER);
        // 这行代码中发生的异常不会抛出！！！？？
        redisTemplate.opsForZSet().incrementScore(key1, pointsRecord.getUserId().toString(), pointsRecord.getPoints());
    }

    /**
     * 查询用户今日获取积分的情况
     *
     * @return
     */
    @Override
    public List<PointsStatisticsVO> getTodayPoints() {

        LocalDateTime begin = DateUtils.getDayStartTime(LocalDateTime.now());
        LocalDateTime end = DateUtils.getDayEndTime(LocalDateTime.now());

        List<PointsRecord> pointsRecords = this.query()
                .select("type, sum(points) as points")
                .eq("user_id", UserContext.getUser())
                .between("create_time", begin, end)
                .groupBy("type")
                .list();

        List<PointsStatisticsVO> list = new ArrayList<>();
        for (PointsRecord pointsRecord : pointsRecords) {
            PointsStatisticsVO pointsStatisticsVO = new PointsStatisticsVO();
            pointsStatisticsVO.setType(pointsRecord.getType().getDesc());
            pointsStatisticsVO.setPoints(pointsRecord.getPoints());
            pointsStatisticsVO.setMaxPoints(pointsRecord.getType().getMaxPoints());
            list.add(pointsStatisticsVO);
        }

        return list;

    }
}
